﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.Model;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class CompanyController : Controller
    {
        private ICompanyService _companyService;
        private ICompanyInformationService _companyInformationService;
        private IHostingEnvironment _hostingEnv;
        public CompanyController(ICompanyService companyService, IHostingEnvironment hostingEnv,
            ICompanyInformationService companyInformationService)
        {
            _companyService = companyService;
            _companyInformationService = companyInformationService;
            _hostingEnv = hostingEnv;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult CompanyLogin()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult CompanyLogin([FromForm]Company company)
        {
            Company testCompany = _companyService.Login(company);
            if (testCompany == null)
            {
                return Json(AjaxResult.ReturnMessage(0, "企业名称或邮箱或密码错误"));
            }
            else
            {
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, testCompany.Id.ToString()));
                // identity.AddClaim(new Claim(ClaimTypes.Email, testCompany.Email));
                identity.AddClaim(new Claim(ClaimTypes.Name, testCompany.Email));
                identity.AddClaim(new Claim(ClaimTypes.Role, testCompany.Role));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, testCompany.Email + testCompany.Role));
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                return Json(AjaxResult.ReturnMessage(1, "登录成功"));
            }
        }

        [Authorize(Roles ="Company")]
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("CompanyLogin", "Company");
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult CompanyRegister()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult CompanyRegister([FromBody]Company company)
        {
            company.Role = "Company";
            company.Status = 0;
            Company testCompany;
            CompanyInformation companyInformation = new CompanyInformation();
            testCompany = _companyService.GetByEmail(company.Email);
            if (testCompany != null)
            {
                return Json(AjaxResult.ReturnMessage(0, "注册失败，该邮箱被占用"));
            }
            testCompany = _companyService.GetByName(company.CompanyName);
            if (testCompany != null)
            {
                return Json(AjaxResult.ReturnMessage(0, "注册失败，该名称被占用"));
            }
            testCompany = _companyService.GetByNumber(company.CompanyNumber);
            if (testCompany != null)
            {
                return Json(AjaxResult.ReturnMessage(0, "注册失败，该工商注册号被占用"));
            }
            _companyService.Register(company);
            companyInformation.CompanyId = company.Id.Value;
            companyInformation.CompanyName = company.CompanyName;
            companyInformation.Email = company.Email;
            _companyInformationService.Add(companyInformation);
            return Json(AjaxResult.ReturnMessage(1, "注册成功"));
        }

        [Authorize(Roles ="Company")]
        [HttpGet]
        public IActionResult CompanyUpdate(string email)
        {
            Company company = _companyService.GetByEmail(email);
            ViewData["Title"] = "重新上传企业信息";
            return View(company);
        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public IActionResult CompanyUpdate([FromBody]Company company)
        {
            Company newCompany;          
            newCompany = _companyService.GetByEmail(User.Identity.Name);
            if (newCompany != null && newCompany.Id.Value != company.Id)
            {
                return Json(AjaxResult.ReturnMessage(0, "上传失败，该企业不存在"));
            }
            newCompany.CompanyNumber = company.CompanyNumber;
            newCompany.BusinessLicense = company.BusinessLicense;
            newCompany.Status = 0;
            _companyService.Update(newCompany);
            return Json(AjaxResult.ReturnMessage(1, "上传成功"));
        }

        [Authorize(Roles ="Admin")]
        [HttpGet]
        public IActionResult CompanyList(int status = 1, int pageIndex = 1)
        {
            IList<Company> companies = new List<Company>();
            companies = _companyService.GetComList(status, pageIndex);
            int pageCount = (int)Math.Ceiling((double)_companyService.GetCount(status) / 20);
            ViewData["PageCount"] = pageCount;
            ViewData["Status"] = status;
            if (pageCount == 0)
            {
                ViewData["PageIndex"] = 0;
            }
            else
            {
                ViewData["PageIndex"] = pageIndex;
            }

            ViewData["Title"] = "企业管理";
            return View(companies);
        }

        [Authorize(Roles ="Admin")]
        [HttpPost]
        public IActionResult UpdateCompany(int id, int status, string remark)
        {                       
            Company company = _companyService.GetId(id);
            if (company == null)
                return Json(AjaxResult.ReturnMessage(0, "审核失败，该企业不存在"));
            company.Status = status;
            company.Remark = remark;
            _companyService.Update(company);
            return Json(AjaxResult.ReturnMessage(1, "审核成功"));
        }

        [Authorize]
        [HttpGet]
        public IActionResult CompanyAudit(int companyId)
        {            
            Company company = _companyService.GetId(companyId);
            ViewData["Title"] = "企业审核信息";
            return View(company);
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [Route("Upload/FormImg")]
        [HttpPost]
        public ActionResult UploadImg(IFormFileCollection files)
        {
            if (files.Count != 1)
            {
                return Json(AjaxResult.ReturnMessage(0, "上传失败，无数据"));
            }
            //返回的文件地址
            List<string> filenames = new List<string>();
            var now = DateTime.Now;
            //文件存储路径
            var filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //获取当前web目录
            var webRootPath = _hostingEnv.WebRootPath;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        #region  图片文件的条件判断
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，该文件不是.gif|.jpg|.jpeg|.png格式"));
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，该文件不是.gif|.jpg|.jpeg|.png格式"));
                        }

                        //判断文件大小    
                        long length = item.Length;
                        if (length > 1024 * 1024 * 2) //2M
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，图片不能大于2M"));
                        }

                        #endregion

                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据                 
                        using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        filenames.Add(filePath + saveName);
                    }
                }
                //return Json(new { returnCode = filenames[0] });
                return Json(AjaxResult.ReturnMessage(1, "上传成功", filenames[0]));
            }
            catch (Exception ex)
            {
                return Json(AjaxResult.ReturnMessage(0, ex.Message));
            }
        }
    }
}
